//一组函数，方法操作的库。原始js库。
var _ = require('underscore')
var Movie = require('../models/movie')
var Comment = require('../models/comment')
var Catetory = require('../models/catetory.js')
var fs = require('fs')
var path = require('path')

//列表页
exports.detail = function(req,res){
	var id = req.params.id
	Movie.update({_id:id},{$inc:{pv:1}},function(err){
		if(err){
			console.log(err);
		}
	})
	Movie.findById(id,function(err,movie){
		Comment
		.find({movie:id})
		.populate('from','name')
		.populate('reply.from reply.to','name')
		.exec(function(err,comments){
			console.log(comments)
			console.log(comments.reply)
			res.render('detail',{
				title:'imooc '+movie.title,
				movie:movie,
				comment:comments
			})
		})
	})
}

//admin update movie
exports.update = function(req,res){
	var id = req.params.id;
	if(id){
		Movie.findById(id,function(error,movie){
			Catetory.find({},function(err,catetories){
				res.render('admin',{
					title:'imooc 后台更新页',
					movie:movie,
					catetories:catetories
				})
			})
		})
	}
}
//admin post movie
exports.save = function(req,res){

	var id = req.body.movie._id;
	var movieObj = req.body.movie;
	var _movie;

	if(req.poster){
		movieObj.poster = req.poster;
	}

	if(id){
		Movie.findById(id,function(err,movie){
			if(err){
				console.log(err);
			}

			_movie = _.extend(movie,movieObj);
			_movie.save(function(err,movie){
				if(err){
					console.log(err);
				}
				res.redirect('/movie/'+movie._id);
			})
		})
	}else{
		_movie = new Movie(movieObj)

		var catetory= _movie.catetory;

		if(!catetory){
			var catetoryName = movieObj.catetoryName;
			if(!catetoryName || catetoryName.trim().length===0){
				catetoryName='默认分类';
			}
			var cate = new Catetory({
				name:catetoryName,
				movies:[]
			});
			cate.save(function(err,catetory){
				if(err){
					console.log(err);
				}
				_movie.catetory = catetory._id;
				catetory = catetory._id;

				_movie.save(function(err,movie){
				if(err){
					console.log(err);
				}

				Catetory.findById(catetory,function(err,catetory){
					catetory.movies.push(movie._id)

					catetory.save(function(err,catetory){
						if(err){
							console.log(err);
						}
						res.redirect('/movie/'+movie._id);
					})
				})

			})
			})
		}else{
			_movie.save(function(err,movie){
				if(err){
					console.log(err);
				}

				Catetory.findById(catetory,function(err,catetory){
					catetory.movies.push(movie._id)

					catetory.save(function(err,catetory){
						if(err){
							console.log(err);
						}
						res.redirect('/movie/'+movie._id);
					})
				})

			})
		}
	}
}

exports.savePoster = function(req,res,next){
	var posterData = req.files.uploadPoster;
	var filePath = posterData.path;
	var originalFileName = posterData.originalFilename;
	console.log(filePath);
	if(originalFileName){
		fs.readFile(filePath,function(err,data){
			var timestamp = Date.now();
			var type = posterData.type.split('/')[1];
			var poster = timestamp+'.'+type;
			var newPath = path.join(__dirname,'../../','/public/upload/'+poster);

			fs.writeFile(newPath,data,function(err){
				req.poster = poster;
				next();
			})
		})
	}
	else{
		next();
	}
}
//admin
exports.new = function(req,res){
	Catetory.find({},function(err,catetories){
		if(err){
			console.log(err)
		}
		res.render('admin',{
			title:'imooc 录入页',
			catetories:catetories,
			movie:{}
		});
	})
}

//lsit
exports.list = function(req,res){
	Movie.fetch(function(err,movies){
		if(err){
			console.log(err);
		}
		res.render('list',{
			title:'imooc 列表页',
			movies:movies
		})
	});
	// res.render('pages/list',{
	// 	title:'imooc 列表页',
	// 	movies:[{
	// 		_id:'1',
	// 		doctor:'何塞·帕迪里亚',
	// 		country:'美国',
	// 		title:'机械战警',
	// 		year:'2014',
	// 		poster:'https://ss0.bdstatic.com/94oJfD_bAAcT8t7mm9GUKT-xh_/timg?image&quality=100&size=b4000_4000&sec=1476794483&di=4ddb1536c6610fccb41a86ba6f2c0425&src=http://b.hiphotos.baidu.com/image/pic/item/d009b3de9c82d15825ffd75c840a19d8bd3e42da.jpg',
	// 		language:'英语',
	// 		flash:'http://vxml.ifengimg.com/swf/ifengFreePlayer_v6.0.7_dm15.swf',
	// 		summary:'2028年，专事军火开发的机器人公司Omni Corp生产了大量装备精良的机械战警，他们被投入到维和和惩治犯罪等行动中，取得显著的效果。罪犯横行的底特律市，嫉恶如仇、正义感十足的警察亚历克斯·墨菲（乔尔·金纳曼饰）遭到仇家暗算，身体受到毁灭性破坏。借助于Omni公司天才博士丹尼特·诺顿（加里·奥德曼饰）最前沿的技术，墨菲以机械战警的形态复活。数轮严格的测试表明，墨菲足以承担起维护社会治安的重任，他的口碑在民众中直线飙升，而墨菲的妻子克拉拉（艾比·考尼什饰）和儿子大卫却再难从他身上感觉亲人的温暖。感知到妻儿的痛苦，墨菲决心向策划杀害自己的犯罪头子展开反击。'
	// 	}]
	// })
}
exports.del = function(req,res){
	var id = req.query.id;

	if(id){
		Movie.remove({_id:id},function(err,movie){
			if(err){
				console.log(err);
			}else{
				res.json({success:1})
			}
		})
	}
}